let encrypt = {}
import CryptoJS from 'crypto-js'
import JsEncrypt from 'jsencrypt'
import Global from './global'

/**
 * AES对称请求数据加密
 */
encrypt.EncryptData = function (data) {
  let key = CryptoJS.enc.Latin1.parse(Global.getRandomAesKey())
  let srcs = CryptoJS.enc.Utf8.parse(data)
  let encrypted = CryptoJS.AES.encrypt(srcs, key, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  })
  return encrypted.toString()
}

/**
 * AES对称请求数据解密
 */
encrypt.DecryptData = function (data) {
  let key = CryptoJS.enc.Latin1.parse(Global.getRandomAesKey())
  let iv   = CryptoJS.enc.Latin1.parse(Global.getRandomAesKey());
  let stime = new Date().getTime()
  let decrypt = CryptoJS.AES.decrypt(data, key, {
    iv: iv,
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  })
  let result = JSON.parse(CryptoJS.enc.Utf8.stringify(decrypt).toString())
  return result
}

encrypt.JsEncrypt = function () {
  let encrypt = new JsEncrypt()
  encrypt.setPublicKey(Global.getPublicKey())
  return encrypt
}

export default encrypt